package core

import (
	"fmt"

	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

// type UnixModel struct {
// 	// gorm.Model
// 	ID        uint           `gorm:"primary_key" json:"id"`
// 	CreatedAt int            `json:"-"`
// 	UpdatedAt int            `json:"-"`
// 	DeletedAt gorm.DeletedAt `sql:"index" json:"-"`
// }

func NewPostgres() *gorm.DB {
	dsn := fmt.Sprintf(
		"host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Asia/Shanghai",
		C.Postgres.Host,
		C.Postgres.Username,
		C.Postgres.Password,
		C.Postgres.Database,
		C.Postgres.Port,
	)
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		L.Errorf("打开数据库失败：%v\n", err)
		return nil
	}
	return db
}

func NewSqlite(dns string) *gorm.DB {
	db, err := gorm.Open(sqlite.Open(dns), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix: "t_", // table name prefix, table for `User` would be `t_users`
			// SingularTable: true, // use singular table name, table for `User` would be `user` with this option enabled
			// NoLowerCase: true, // skip the snake_casing of names
			// NameReplacer: strings.NewReplacer("CID", "Cid"), // use name replacer to change struct/field name before convert it to db name
		},
	})
	if err != nil {
		L.Errorf("打开数据库失败：%v\n", err)
		return nil
	}
	return db
}

func NewGorm(sqltype string) *gorm.DB {
	switch sqltype {
	case "postgres":
		return NewPostgres()
	case "sqlite":
		return NewSqlite(C.Sqlite)
	case "memory":
		return NewSqlite("file::memory:?cache=shared")
	default:
		return NewPostgres()
	}
}
